package com.tte.common.producer.test2;

import java.util.ArrayList;

/**
 * Two2
 */
public class Two2 {
    public static void main(String[] args) {
        //缓冲池
        ArrayList<Integer> a = new ArrayList<Integer>(5);
        //启动生产者
        new Thread(new producter(a)).start();
        //启动消费者;
        new Thread(new Consumer(a)).start();
    }
}

class producter2 implements Runnable {
    ArrayList<Integer> a;

    public producter2(ArrayList<Integer> a) {
        this.a = a;
    }


    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //对缓冲池加锁
            synchronized (a) {
                //进行判断
                if(a.size()<5){
                    a.add(1);
                    System.out.println("正在生产，当前剩余"+a.size());
                    //当生产过后要通知一下消费者可以取了
                    a.notifyAll();
                }else {
                    System.out.println("产量太多进入等待");
                    try {
                        //当满了以后要注意等待
                        a.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class Consumer2 implements Runnable {
    ArrayList<Integer> a;

    public Consumer2(ArrayList<Integer> a) {
        this.a = a;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (a) {
                if(a.size()>0){
                    a.remove(0);
                    System.out.println("消费了，当前剩余"+a.size());
                    //通知生产者生产
                    a.notifyAll();
                }else {
                    System.out.println("产量不足，进入等待");
                    try {
                        //当缓冲池空的时候要等待
                        a.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}